/**
 * @file 检查事件支持情况
 */

const cache = {};

export default (source, tagName = 'input') => {
    const events = Array.isArray(source) ? source : [source];
    const queues = events.map(event => (
        new Promise((resolve) => {
            if (Object.prototype.hasOwnProperty.call(cache, event)) {
                resolve(cache[event]);

                return;
            }

            const complete = (flag) => {
                // eslint-disable-next-line
                clearTimeout(timer);
                cache[event] = flag;
                resolve(flag);
            };
            const timer = setTimeout(() => complete(false), 100);
            const $el = document.createElement(tagName);
            const trigger = document.createEvent('HTMLEvents');

            $el.addEventListener(event, () => complete(true));
            trigger.initEvent(event, true, true);
            $el.dispatchEvent(trigger);
        })
    ));

    return Promise.all(queues);
};
